package com.rockcent.third.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.lib.domain.Customer;
import com.rockcent.mall.lib.domain.CustomerCouponWallet;
import com.rockcent.mall.lib.domain.MerchantCoupon;
import com.rockcent.mall.lib.domain.UserInfo;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.JunshiReqDto;
import com.rockcent.mall.lib.repository.CustomerCouponWalletRepository;
import com.rockcent.mall.lib.repository.CustomerRepository;
import com.rockcent.mall.lib.repository.MerchantCouponRepository;
import com.rockcent.third.Routes;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by caihongli on 2017/5/16.
 * 骏视直播
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class JunshiAPIController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(JunshiAPIController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private MerchantCouponRepository merchantCouponRepository;
    @Autowired
    private CustomerCouponWalletRepository customerCouponWalletRepository;

    @RequestMapping(value = Routes.CGI_BIN_JUNSHI_REWARD, method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult reward(@RequestBody JunshiReqDto dto, @RequestHeader("accessToken") String accessToken, HttpServletRequest request) {
        RestDoing doing = jr -> {
            if (StringUtils.isEmpty(accessToken)) {
                jr.remind("accessToken不能为空",log);
                return;
            }
            String channelId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + accessToken).get();
            if (StringUtils.isEmpty(channelId)) {
                jr.custom("10002", "未经过授权访问", log);
                return;
            }
            if (null == dto) {
                jr.remind("参数有误",log);
                return;
            }
            if(StringUtils.isEmpty(dto.getType())) {
                jr.remind("类型不能为空",log);
                return;
            }
            if(StringUtils.isNotEmpty(dto.getType())) {
                if(!(dto.getType().equals("DISCOUNT") || dto.getType().equals("VOUCHERS"))) {
                    jr.remind("非法类型",log);
                    return;
                }
            }
            if(StringUtils.isEmpty(dto.getMobile())) {
                jr.remind("手机号码不能为空",log);
                return;
            }
            if(dto.getAmount()==null) {
                jr.remind("金额不能为空",log);
                return;
            }
            Long couponId = null;
            if(dto.getAmount()!=null) {
                if(dto.getAmount().intValue()==10) {
                    couponId=123L;
                } else if(dto.getAmount().intValue()==5) {
                    couponId=125L;
                } else if(dto.getAmount().intValue()==20) {
                    couponId=126L;
                }
            }
            Customer customer = customerRepository.findByMobile(dto.getMobile());
            if(null==customer) {
                jr.remind("手机号码不存在",log);
                return;
            }
            if(CouponType.valueOf(dto.getType())==CouponType.DISCOUNT) {
                couponId = 124L;
            }
            if(couponId==null) {
                jr.remind("参数有误",log);
                return;
            }
            List<CustomerCouponWallet> customerCouponWalletList = customerCouponWalletRepository.findByCustomerIdAndCouponIdAndSource(customer.getId(), couponId, CustomerCouponWalletSource.JUNSHI);
            //卡卷校验
            MerchantCoupon merchantCoupon = merchantCouponRepository.findOne(couponId);
            if (merchantCoupon == null) {
                jr.remind(MerchantCoupon.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            if (customerCouponWalletList!=null && customerCouponWalletList.size() > 0) {
                if (CouponDrawLimit.ALL == merchantCoupon.getDrawLimit() && customerCouponWalletList.size() > merchantCoupon.getLimitCount()) {
                    jr.remind("卡券领取数量超过限制:" + merchantCoupon.getName(),log);
                    return;
                }
            }
            if (MerchantCouponStatus.ISSUED != merchantCoupon.getStatus()) {
                jr.remind(merchantCoupon.getName() + "卡卷状态不正确,已下架或过期",log);
                return;
            }
            if (merchantCoupon.getLeaveTotal() == 0) {
                jr.remind(merchantCoupon.getName() + ":卡卷已经领完",log);
                return;
            }
            //保存我的卡卷
            CustomerCouponWallet couponWallet = new CustomerCouponWallet();
            couponWallet.setMerchantId(merchantCoupon.getMerchantId());
            couponWallet.setCouponId(merchantCoupon.getId());
            couponWallet.setCustomerId(customer.getId());
            couponWallet.setMallId(merchantCoupon.getMallId());
            couponWallet.setSource(CustomerCouponWalletSource.JUNSHI);
            couponWallet.setStatus(CustomerCouponWalletStatus.TO_USE);
            couponWallet.setCustomerName(customer.getNickName());
            customerCouponWalletRepository.save(couponWallet);
            //更新新卡卷库存
            merchantCoupon.setLeaveTotal(merchantCoupon.getLeaveTotal() - 1);
            merchantCouponRepository.save(merchantCoupon);
        };
        return doing.go(request, log);
    }

}